﻿using System;
using System.Web.Http;
using System.Web.Http.SelfHost;
namespace Zeus.SelfHost
{
    using Configure;
    public class ZeusSelfHostPower : IDisposable
    {
        private HttpSelfHostServer server;
        public void Coming(IZeusSelfHostConfigure zeusSelfHostConfigure, Action<HttpSelfHostConfiguration> extensionConfiguration)
        {
            var address = new Uri(zeusSelfHostConfigure.SelfHostString);
            var config = new HttpSelfHostConfiguration(address);
            if (zeusSelfHostConfigure.ExceptionHandler != null)
            {
                config.ConfigExceptionHandler(zeusSelfHostConfigure.ExceptionHandler);
            }
            if (zeusSelfHostConfigure.ZLogger != null)
            {
                config.EnableZLogger(zeusSelfHostConfigure.ZLogger, zeusSelfHostConfigure.ZLoggerContext);
            }
            config.BuildDependencyContainer();
            extensionConfiguration?.Invoke(config);
            config.MapHttpAttributeRoutes();
          
            server = new HttpSelfHostServer(config);
            server.OpenAsync().Wait();
        }

        public void Dispose()
        {
            server.CloseAsync().Wait();
            server.Dispose();
        }
    }
}
